import logging
from datetime import datetime
from sqlalchemy.orm import Session
from backend.database import SessionLocal
from backend.models.shop import Shop
# from backend.wingknife.routes import run_wingknife_process
from backend.routes.shop import get_products_by_shop
from backend.wingknife.schemas import WingknifeRunRequest
from fastapi import HTTPException
import asyncio
import traceback

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

async def run_shop_processes():
    """执行所有启用状态的店铺流程"""
    try:
        db = next(get_db())
        # 查询所有启用状态的店铺
        enabled_shops = db.query(Shop).filter(Shop.enabled == "启用").all()
        
        for shop in enabled_shops:
            try:
                if not shop.store_id:
                    logging.warning(f"店铺 {shop.shop_name}(ID: {shop.id}) 没有 store_id，跳过执行")
                    continue
                    
                # 调用影刀流程
                await get_products_by_shop(
                    shop_id=shop.store_id,
                    db=db
                )
                logging.info(f"成功触发执行店铺 {shop.shop_name}(ID: {shop.id}, Store ID: {shop.store_id}) 的流程")
            except Exception as e:
                error_msg = f"触发执行店铺 {shop.shop_name}(ID: {shop.id}, Store ID: {shop.store_id}) 的流程失败: {str(e)}\n{traceback.format_exc()}"
                logging.error(error_msg)
                continue

            #等待1分钟
            await asyncio.sleep(60)
                
    except Exception as e:
        error_msg = f"执行店铺流程任务失败: {str(e)}\n{traceback.format_exc()}"
        logging.error(error_msg)
    finally:
        db.close()

def run_shop_processes_wrapper():
    """包装异步函数的同步包装器"""
    asyncio.run(run_shop_processes())

def add_jobs(scheduler):
    """添加所有定时任务"""
    try:
        # 添加一个每天凌晨2点执行的店铺流程任务
        # scheduler.add_job(
        #     run_shop_processes_wrapper,  # 使用同步包装器
        #     'cron',
        #     hour=19,  # 每天凌晨2点执行
        #     minute=47,
        #     id='shop_processes_job',
        #     replace_existing=True,
        #     start_date="2025-06-17 00:00:00",
        #     timezone='Asia/Shanghai'  # 指定时区
        # )
        # logging.info("成功添加店铺流程定时任务")
        logging.info("定时任务暂时关闭")
    except Exception as e:
        logging.error(f"添加定时任务失败: {str(e)}")
        raise

    # 这里可以添加更多任务
    # 例如：
    # scheduler.add_job(
    #     another_job,
    #     'cron',
    #     hour=9,
    #     minute=0,
    #     id='daily_job',
    #     replace_existing=True
    # ) 